package org.benjamin.lending.controller.admin;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.commons.UserSession;
import org.benjamin.lending.domain.BJUIData;
import org.benjamin.lending.domain.BJUIResult;
import org.benjamin.lending.domain.BorrowIndex;
import org.benjamin.lending.domain.entity.BorrowInfo;
import org.benjamin.lending.domain.entity.BorrowProduct;
import org.benjamin.lending.domain.entity.PaymentMethod;
import org.benjamin.lending.domain.form.BorrowVerifyForm;
import org.benjamin.lending.service.BorrowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;

import java.util.List;

/**
 * Created by xywen on 2017/5/30.
 */
@Controller("adminBorrowController")
@RequestMapping("admin/borrow")
public class AdminBorrowController {

    private final Logger logger = LogManager.getLogger();

    @Autowired
    private BorrowService borrowService;

    @RequestMapping(value = "index")
    public String index(BorrowIndex borrowIndex,ModelMap modelMap){
        Page<BorrowInfo> borrowInfos = this.borrowService.findBorrowInfoList(borrowIndex.getPageRequest());
        modelMap.addAttribute("borrowInfos",borrowInfos);
        return "borrow/index";
    }


    @GetMapping(value = "create")
    public String toCreate(ModelMap modelMap){
    	List<BorrowProduct> borrowProducts = this.borrowService.findProductList();
    	modelMap.addAttribute("borrowProducts",borrowProducts);
        modelMap.addAttribute("paymentMethod", PaymentMethod.values());
        modelMap.addAttribute("borrowInfo",new BorrowInfo());
        return "borrow/create";
    }

    @ResponseBody
    @PostMapping("create")
    public BJUIResult doCreate(@Valid BorrowInfo borrowInfo, BindingResult bindingResult){
        if(!bindingResult.hasErrors()){
            logger.info("创建借款标");
            try{
                this.borrowService.createBorrowInfo(borrowInfo);
                return BJUIResult.defaultSuccess();
            }catch(Exception e){
                logger.error(e.getMessage(),e);
                return BJUIResult.defaultFail(e.getMessage());
            }

        }
        return BJUIResult.defaultFail("提交失败");
    }

    @ResponseBody
    @RequestMapping(value = "data")
    public BJUIData data(BorrowIndex borrowIndex){
        Page<BorrowInfo> borrowInfos = this.borrowService.findBorrowInfoList(borrowIndex.getPageRequest());
        return new BJUIData(borrowInfos);
    }

    @RequestMapping(value = "edit")
    public String edit(Integer id,ModelMap modelMap){
        BorrowInfo borrowInfo = this.borrowService.getBorrowById(id);
        modelMap.addAttribute("paymentMethod", PaymentMethod.values());
        modelMap.addAttribute("borrowInfo",borrowInfo);
        return "borrow/edit";
    }
    
    @ResponseBody
    @PostMapping(value = "doEdit")
    public BJUIResult doEdit(BorrowInfo borrowInfo){
    	try{
    		this.borrowService.updateEntity(borrowInfo);
    		return BJUIResult.defaultSuccess();
    	}catch(Exception e){
    		logger.error(e.getMessage(),e);
    	}
    	return BJUIResult.defaultFail("提交失败");
    }
    
    
    @PostMapping(value = "toAuditing")
    public String auditing(Integer borrowId,ModelMap modelMap){
    	Assert.notNull(borrowId,"出现异常，审核借款标编号不能为空");
    	BorrowInfo borrowInfo = this.borrowService.getBorrowById(borrowId);
    	Assert.notNull(borrowInfo,"页面出现问题[200000]");
    	BorrowVerifyForm borrowVerify = new BorrowVerifyForm();
    	borrowVerify.setType(borrowInfo.getStatus().toString());
    	borrowVerify.setBorrowId(borrowInfo.getId());
    	modelMap.addAttribute("borrowVerify",borrowVerify);
    	return "borrow/auditing";
    }
    
    
    @ResponseBody
    @PostMapping(value = "doAuditing")
    public BJUIResult doAuditing(BorrowVerifyForm borrowVerify){
    	try{
    		String username = UserSession.getSessionUserName();
    		this.borrowService.auding(borrowVerify.getType(), borrowVerify.getMessage(), borrowVerify.getResult(), borrowVerify.getBorrowId(), username);
    		BJUIResult.defaultSuccess();
    	}catch(Exception e){
    		logger.error(e.getMessage(),e);
    	}
    	return BJUIResult.defaultFail("错误");
    }
    
    @RequestMapping(value = "product_index")
    public String productIndex(ModelMap modelMap) {
    	List<BorrowProduct> borrowProducts = this.borrowService.findProductList();
    	modelMap.addAttribute("borrowProducts",borrowProducts);
    	modelMap.addAttribute("borrowProduct",new BorrowProduct());
    	return "admin_borrow.productIndex";
    }
    
    @RequestMapping(value = "add_product")
    public String addProduct(BorrowProduct borrowProduct, ModelMap modelMap) {
    	logger.info("开始执行保存产品配置信息");
    	this.borrowService.addProduct(borrowProduct);
    	logger.info("结束产品配置信息");
    	return "admin.success";
    }
}
